package com.hsh.maoduo.service.impl;

import com.hsh.maoduo.common.Result;
import com.hsh.maoduo.constant.YDPathConstants;
import com.hsh.maoduo.constant.YTGJPathConstants;
import com.hsh.maoduo.constant.common.DateConstants;
import com.hsh.maoduo.constant.common.GlobalPathConstants;
import com.hsh.maoduo.pojo.dto.ShopGoodsDTO;
import com.hsh.maoduo.pojo.other.yd.JDExport;
import com.hsh.maoduo.pojo.other.yd.YDExport;
import com.hsh.maoduo.pojo.other.yd.YDImport;
import com.hsh.maoduo.pojo.other.yd.YDSend;
import com.hsh.maoduo.pojo.vo.ShopGoodsVO;
import com.hsh.maoduo.service.OrderGoodsService;
import com.hsh.maoduo.service.ShopGoodsService;
import com.hsh.maoduo.service.YDService;
import com.hsh.maoduo.util.MyBeanUtils;
import com.hsh.maoduo.util.POIExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class YDServiceImpl implements YDService {

    @Resource
    private OrderGoodsService orderGoodsService;

    @Resource
    private ShopGoodsService shopGoodsService;

    @Resource
    GoodsServiceImpl goodsService;

    /**
     * 京东和美团生成导入文档
     */
    @Override
    public int writeImportExcel(String jdPassword) {
        String dateStr = DateConstants.PURE_DATE_FORMAT.format(new Date());
        //韵达导入文档
        List<YDImport> ydImportList = new ArrayList<>();
        //读取京东导入文档并筛选符合条件的数据
        jdExportsToYDImports(ydImportList, jdPassword);
        //写入韵达导入文档
        int rowNum = POIExcelUtil.write(YDPathConstants.YD_IMPORT_PATH_PRE
                        + YDPathConstants.YD_IMPORT_NAME_PRE
                        + dateStr
                        + GlobalPathConstants.XLSX_SUF
                , ydImportList, YDImport.class);
        return rowNum;
    }


    /**
     * 生成揽收文件
     */
    @Override
    public Result writeSendExcel(String dateStr) {
        Date date = null;
        try {
            date = DateConstants.PURE_DATE_FORMAT.parse(dateStr);
        } catch (ParseException e) {
            return Result.success(writeSendExcel());
        }
        return Result.success(writeSendExcel(date));
    }

    /**
     * 生成揽收文件
     */
    private String writeSendExcel() {
        return writeSendExcel(new Date());
    }

    /**
     * 生成揽收文件
     */
    private String writeSendExcel(Date date) {
        String dateStr = DateConstants.PURE_DATE_FORMAT.format(date);
        List<YDExport> ydExportList = POIExcelUtil.reads(YDPathConstants.YD_EXPORT_PATH_PRE
                , YDPathConstants.YD_EXPORT_NAME_PRE + dateStr
                , YDExport.class);
        //将读取的数据转成order并写入数据库
        int insertOrderNum = 0;
        try {
            insertOrderNum = orderGoodsService.insertByExport(ydExportList);
        } catch (Exception e) {
            log.error("插入数据库失败,原因：{}", e.getMessage());
        }
        List<YDSend> ydSendList = new ArrayList<>();
        //将快递单号写入到揽收文件
        for (YDExport ydExport : ydExportList) {
            ydSendList.add(new YDSend(ydExport.getExpressNum()));
        }
        int ydRowNum = POIExcelUtil.write(YDPathConstants.YD_SEND_PATH_PRE
                        + YDPathConstants.YD_SEND_NAME_PRE
                        + dateStr
                        + GlobalPathConstants.XLSX_SUF
                , ydSendList, YDSend.class);
        int allYdRowNum = POIExcelUtil.write(YTGJPathConstants.ALL_YDGJ_SEND_PATH_PRE
                        + YDPathConstants.YD_SEND_NAME_PRE
                        + dateStr
                        + GlobalPathConstants.XLSX_SUF
                , ydSendList, YDSend.class);
        return "京东--新增订单数量：" + insertOrderNum + "，写入揽收文件数量：" + allYdRowNum;
    }


    /**
     * 读取京东导入文档并筛选符合条件的数据
     *
     * @param ydImportList
     * @return
     */
    private int jdExportsToYDImports(List<YDImport> ydImportList, String password) {
        //读取京东导入文档
        List<JDExport> jdExportList = POIExcelUtil.reads(YDPathConstants.JD_EXPORT_PATH_PRE
                , YDPathConstants.JD_EXPORT_NAME_PRE + DateConstants.NORM_DATE_FORMAT.format(new Date())
                , JDExport.class, password);
        //筛选符合条件的数据
        jdExportList = jdExportList.stream()
                .filter(v -> StringUtils.hasLength(v.getGoodsName()))//商品名称不为空
                .filter(v -> !v.getGoodsName().startsWith(YDPathConstants.JD_EXCLUDE_GOODS_NAME_PRE))//去除赠品
                .filter(v -> YDPathConstants.JD_ORDER_STATE_WAIT_SEND.equals(v.getOrderState()))//筛选订单状态为“等待发货”
                .collect(Collectors.toList());
        jdExportList = setJdExportGoodsInfo(jdExportList);
        //去除库存不足的订单
        Collections.reverse(jdExportList);
        jdExportList = goodsService.removeOutOfStockOrders(jdExportList);
        int oldSize = ydImportList.size();
        //遍历每条数据  京东导出 -> 韵达导入
        for (JDExport jdExport : jdExportList) {
            YDImport ydImport = MyBeanUtils.copy(jdExport, YDImport.class);
            //设置默认值
            ydImport.init();
            ydImportList.add(ydImport);
        }
        return ydImportList.size() - oldSize;
    }

    private List<JDExport> setJdExportGoodsInfo(List<JDExport> jdExportList) {
        List<JDExport> newList = new ArrayList<>();
        //查询所有的店铺商品id和
        List<ShopGoodsDTO> shopGoodsDTOList = shopGoodsService.selectGoodsNameList(new ShopGoodsVO());
        Map<String, ShopGoodsDTO> goodsInfoMap =
                shopGoodsDTOList.stream().collect(Collectors.toMap(ShopGoodsDTO::getShopGoodsId, Function.identity()));
        for (JDExport jdExport : jdExportList) {
            //商品信息 = 商品简称 * 商品数量
            String goodsSimpleName = "";
            ShopGoodsDTO shopGoodsDTO = goodsInfoMap.get(jdExport.getGoodsId());
            Integer weight = 0;
            if (shopGoodsDTO != null) {
                goodsSimpleName = shopGoodsDTO.getGoodsInfo();
                weight = shopGoodsDTO.getWeight();
            }
            if (Strings.isBlank(goodsSimpleName)) {
                goodsSimpleName = YDPathConstants.DEFAULT_SIMPLE_NAME;
            }
            if (goodsSimpleName.startsWith("虚拟赠品") || goodsSimpleName.startsWith("测试商品")) {
                continue;
            }
            //设置商品信息 ： 商品名称 * 商品数量
            int num = jdExport.getNum();
            if (goodsSimpleName.matches(".*\\*\\d+")) {
                String[] split = goodsSimpleName.split("\\*");
                num = Integer.parseInt(split[1]) * jdExport.getNum();
                goodsSimpleName = split[0];
            }
            jdExport.setGoodsName(goodsSimpleName);
            jdExport.setNum(num);
            jdExport.setGoodsInfo(goodsSimpleName + "*" + num);
            weight = weight == null ? 0 : weight;
            jdExport.setWeight(weight * num);
            //判断订单id是否在list中存在，存在需要合并订单，不存在不处理
            boolean isRepeat = false;
            for (JDExport newJdExport : newList) {
                if (newJdExport.getOrderNo().equals(jdExport.getOrderNo())) {
                    newJdExport.setGoodsInfo(newJdExport.getGoodsInfo() + "；" + jdExport.getGoodsInfo());
                    newJdExport.setWeight(newJdExport.getWeight() + jdExport.getWeight());
                    isRepeat = true;
                }
            }
            if (!isRepeat) {
                newList.add(jdExport);
            }
        }
        jdExportList = newList;
        return jdExportList;
    }

}
